<template>
    <div class="pss-main-oper">
        <div class="pss-main-body" @click.stop="closePop"></div>
        <div class="pss-main-pop">
            <div class="pss-pop-top">
                <h3>操作员新增</h3>
                <i class="el-icon-error" style="color: #FF524A;position:absolute;right: 20px;font-size: 20px" @click="closePop"></i>
            </div>
            <div class="info-module">
                <el-form ref="operInfo"  status-icon :model="operInfo" :rules="rules" class="pss-plan-form" style="padding-top: 10px; border-right: 1px #ccc solid;width: 260px">
                    <div style="display: flex">
                        <span class="form-label-name"><span style="color:red">*</span>操作员姓名</span>
                        <el-form-item prop="operName">
                            <el-input v-model="operName" placeholder="请输入" size="mini" @blur="judgeNameRepeat(operName, '','')"></el-input>
                        </el-form-item>
                    </div>
                    <div style="display: flex">
                        <span class="form-label-name"><span style="color:red">*</span>操作员号码</span>
                        <el-form-item  prop="operPhone">
                            <el-input v-model="operPhone" placeholder="请输入" size="mini" maxlength="11" @blur="judgeNameRepeat('', '',operPhone)"></el-input>
                        </el-form-item>
                    </div>
<!--                    <el-form-item label="*操作员角色">
                        <el-select v-model="operRole" placeholder="请选择" size="small">
                            <el-option label="区域一" value="shanghai"></el-option>
                            <el-option label="区域二" value="beijing"></el-option>
                        </el-select>
                    </el-form-item>-->
                    <div style="display: flex">
                        <span class="form-label-name"><span style="color:red">*</span>操作员账号</span>
                        <el-form-item prop="operCount">
                            <el-input v-model="operCount" placeholder="请输入" size="mini" :disabled="updateOperFlag" @blur="judgeNameRepeat('', operCount,'')"></el-input>
                        </el-form-item>
                    </div>
                    <div style="display: flex">
                        <span class="form-label-name"><span style="color:red">*</span>操作员权限</span>
                        <el-form-item prop="operPermission">
                            <el-select v-model="operPermission" placeholder="请选择" size="small">
                                <el-option label="集团管理员" value="1"></el-option>
                                <el-option label="集团操作员" value="2"></el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                    <div style="display: flex" v-show="newOperFlag">
                        <span class="form-label-name"><span style="color:red">*</span>操作员密码</span>
                        <el-form-item prop="operPassword">
                            <el-input v-model="operPassword" placeholder="请输入" size="mini" show-password @focus="showTopic=true"></el-input>
                        </el-form-item>
                    </div>
                    <div style="color: red;font-size: 12px;padding-top: 10px;position: absolute;bottom: 0"  v-show="newOperFlag && showTopic">*密码必须包含字母、数字和特殊符号,长度至少八位</div>
                </el-form>
                <div class="associates-box">
                    <h2><span style="color: red">*</span>操作员管辖组</h2>
                    <div class="associates-box-tree">
                        <el-tree
                            ref="groupTree"
                            :data="groupList"
                            :props="defaultProps"
                            node-key="groupId"
                            show-checkbox
                            @check-change="handleCheckChange">
                        </el-tree>
                    </div>
                </div>
            </div>
            <el-form ref="form2"  class="pss-plan-form" style="padding:10px 30px 20px;text-align: center">
                <el-form-item>
                    <el-button type="primary" @click="submit" size="mini">确定</el-button>
                    <el-button size="mini" @click="closePop">取消</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
import {dateFormat} from '@/base/utils.js'

export default {
    props:['newOperFlag','updateOperFlag','operInfoObject'],
    data(){
        let checkName = (rule, value, callback) => {
            setTimeout(() => {
                if (!this.operName){
                    callback(new Error('操作员姓名不能为空'));
                }else {
                    if (this.nameRepeatFlag) {
                        callback(new Error('该集团订购下名称重复'));
                    }else {
                        callback();
                    }
                }
            }, 500);
        };
        let checkAccount = (rule, value, callback) => {
            setTimeout(() => {
                if (!this.operCount){
                    callback(new Error('操作员账号不能为空'));
                }else {
                    if (this.accountRepeatFlag) {
                        callback(new Error('该集团订购下账号重复'));
                    }else {
                        callback();
                    }
                }
            }, 500);
        };
        let checkPhone = (rule, value, callback) => {
            setTimeout(() => {
                if (!this.operPhone){
                    callback(new Error('操作员号码不能为空'));
                }else {
                    if (this.phoneRepeatFlag) {
                        callback(new Error('该集团订购下号码重复'));
                    }else {
                        callback();
                    }
                }
            }, 500);
        };
        let checkPassword = (rule, value, callback) => {
            this.showTopic = false;
            let passwordReg = new RegExp('(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,20}');
            if (!this.operPassword){
                callback(new Error('操作员密码不能为空'));
            }else {
                if (!passwordReg.test(this.operPassword) || this.operPassword.length < 8) {
                    callback(new Error('请输入符合要求的密码'));
                } else {
                    callback();
                }
            }
        };
        return {
            operInfo: {},
            operName: '',
            operPhone: '',
            operRole: '',
            operCount: '',
            operPermission: '',
            operPassword: '',
            groupList: [],
            defaultProps: {
                children: 'childGroupList',
                label: 'groupName'
            },
            selectGroup: [],
            nameRepeatFlag: false,
            accountRepeatFlag: false,
            phoneRepeatFlag: false,
            rules: {
                operName:[{validator: checkName,trigger: 'blur'}],
                operPhone:[{validator: checkPhone,trigger: 'blur'}],
                operCount:[{validator: checkAccount,trigger: 'blur'}],
                operPermission:[{required:true,trigger: 'blur',message:"请选择操作员权限"}],
                operPassword:[{validator:checkPassword,trigger: 'blur'}],
            },
            showTopic:false,
        }
    },
    methods:{
        submit(){
            if(this.newOperFlag){
                this.newOperSubmit()
            }else if(this.updateOperFlag){
                this.updateOperSubmit()
            }
        },
        infoDeal(){
            this.operName = this.operInfoObject.userName;
            this.operPhone = this.operInfoObject.userMsisdn;
            //this.operRole = this.operInfoObject;
            this.operCount = this.operInfoObject.userAcct;
            this.operPermission = this.operInfoObject.duty;
            this.selectGroupSearch();
        },
        closePop(){
            this.operName='';
            this.operPhone='';
            this.operRole='';
            this.operCount='';
            this.operPermission='';
            this.operPassword='';
            this.groupList=[];
            this.selectGroup=[];
            this.phoneRepeatFlag = false;
            this.nameRepeatFlag = false;
            this.accountRepeatFlag = false;
            this.$emit('emClosePop');
            this.$refs['operInfo'].resetFields();
        },
        //选择组
        handleCheckChange(data){},
        selectGroupSearch(){
            let param = {
                "userId": this.operInfoObject.userId,
            }
            this.$http.post('/lbs/usercenter/group/qryFirst2ThirdGroupInfo',param).then(res => {
                if(res.data.retCode == '0'){
                    this.groupList = res.data.data.orderGroupList;
                    if (this.updateOperFlag){
                        this.selectGroup = res.data.data.operateGroupList;
                        this.$refs.groupTree.setCheckedKeys(this.selectGroup);
                    }
                }else{
                    this.$message({
                        message: res.data.retMsg,
                        type: 'error'
                    });
                }
            })
        },
        async newOperSubmit() {
            /*let judgeRes = await this.judgeNameRepeat(this.operName, '','');
            if (judgeRes.data.retCode == '0') {
                if (judgeRes.data.data == '1') {
                    this.nameRepeatFlag = true;
                    return;
                }else{
                    this.nameRepeatFlag = false;
                }
            } else {
                this.$message({
                    message: judgeRes.data.retMsg,
                    type: 'error'
                });
                return;
            }
            let judgeRes1 = await this.judgeNameRepeat('', this.operCount,'');
            if (judgeRes1.data.retCode == '0') {
                if (judgeRes1.data.data == '1') {
                    this.accountRepeatFlag = true;
                    return;
                }else{
                    this.accountRepeatFlag = false;
                }
            } else {
                this.$message({
                    message: judgeRes1.data.retMsg,
                    type: 'error'
                });
                return;
            }
            let judgeRes2 = await this.judgeNameRepeat('', '',this.operPhone);
            if (judgeRes2.data.retCode == '0') {
                if (judgeRes2.data.data == '1') {
                    this.phoneRepeatFlag = true;
                    return;
                }else{
                    this.phoneRepeatFlag = false;
                }
            } else {
                this.$message({
                    message: judgeRes2.data.retMsg,
                    type: 'error'
                });
                return;
            }*/
            if(this.nameRepeatFlag){
                return;
            }else if (this.accountRepeatFlag){
                return;
            }else if (this.phoneRepeatFlag){
                return;
            }
            let adminGroupIds = this.$refs.groupTree.getCheckedNodes();
            adminGroupIds = adminGroupIds.filter(item => {
                return (item.childGroupList && item.childGroupList.length == 0) || !item.childGroupList;
            })
            let adminGroupIdsKey = adminGroupIds.map(item => {
                return item.personId;
            })
            if (this.operPhone.length != '11' || !/^\d+$/.test(this.operPhone)) {
                this.$message({
                    message: '请输入正确的电话号码',
                    type: 'warning'
                });
                return;
            }
            let passwordReg = new RegExp('(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,20}');
            if (!passwordReg.test(this.operPassword) || this.operPassword.length<8) {
                this.$message({
                    message: '请输入符合要求的密码',
                    type: 'warning'
                });
                return;
            }
            let param = {
                "userAcct": this.operCount,
                "userPassword": this.operPassword,
                "userMsisdn": this.operPhone,
                "userName": this.operName,
                "duty": this.operPermission,
                "cityId": '',
                "adminGroupIds": JSON.stringify(adminGroupIdsKey)
            }
            this.$http.post('/lbs/usercenter/operator/createOperator', param).then(res => {
                if (res.data.retCode == '0') {
                    this.$message({
                        message: res.data.retMsg,
                        type: 'success'
                    });
                    this.closePop()
                } else {
                    this.$message({
                        message: res.data.retMsg,
                        type: 'error'
                    });
                }
            })
        },
        getSimpleCheckedNodes(store) {
            const checkedNodes = [];
            const traverse = function(node) {
                const childNodes = node.root ? node.root.childNodes : node.childNodes;

                childNodes.forEach(child => {
                    if (child.checked) {
                        checkedNodes.push(child.data);
                    }
                    if (child.indeterminate) {
                        traverse(child);
                    }
                });
            };
            traverse(store)
            return checkedNodes;
        },
        async updateOperSubmit() {
            //let adminGroupIds = this.$refs.groupTree.getCheckedNodes();
            let adminGroupIds = this.getSimpleCheckedNodes(this.$refs.groupTree.store);
            // adminGroupIds = adminGroupIds.filter(item => {
            //     return (item.childGroupList && item.childGroupList.length == 0) || !item.childGroupList;
            // })
            let adminGroupIdsKey = adminGroupIds.map(item => {
                return item.groupId;
            })
            let updateType = '1';
            if (this.operInfoObject.userName == this.operName
                && this.operInfoObject.userMsisdn == this.operPhone
                && this.operInfoObject.duty == this.operPermission
                && (adminGroupIdsKey.toString() == this.selectGroup.toString() || (adminGroupIdsKey.length == 0 && this.selectGroup.length == 0))) {
                this.$message({
                    message: '未作修改，请勿提交',
                    type: 'warning'
                });
                return;
            } else if (adminGroupIdsKey.join(',') != this.selectGroup.join(',')) {
                updateType = '2';
            }
            /*if (this.operName != this.operInfoObject.userName) {
                let judgeRes = await this.judgeNameRepeat(this.operName, '','');
                if (judgeRes.data.retCode == '0') {
                    if (judgeRes.data.data == '1') {
                        this.nameRepeatFlag = true;
                        return;
                    }else{
                        this.nameRepeatFlag = false;
                    }
                } else {
                    this.$message({
                        message: judgeRes.data.retMsg,
                        type: 'error'
                    });
                    return;
                }
            }
            if (this.operCount != this.operInfoObject.userAcct) {
                let judgeRes1 = await this.judgeNameRepeat('', this.operCount,'');
                if (judgeRes1.data.retCode == '0') {
                    if (judgeRes1.data.data == '1') {
                        this.accountRepeatFlag = true;
                        return;
                    }else{
                        this.accountRepeatFlag = false;
                    }
                } else {
                    this.$message({
                        message: judgeRes1.data.retMsg,
                        type: 'error'
                    });
                    return;
                }
            }
            if (this.operPhone != this.operInfoObject.userMsisdn) {
                let judgeRes2 = await this.judgeNameRepeat('', '',this.operPhone);
                if (judgeRes2.data.retCode == '0') {
                    if (judgeRes2.data.data == '1') {
                        this.phoneRepeatFlag = true;
                        return;
                    }else{
                        this.phoneRepeatFlag = false;
                    }
                } else {
                    this.$message({
                        message: judgeRes2.data.retMsg,
                        type: 'error'
                    });
                    return;
                }
            }*/
            if(this.nameRepeatFlag){
                return;
            }else if (this.accountRepeatFlag){
                return;
            }else if (this.phoneRepeatFlag){
                return;
            }
            if (this.operPhone.length != '11' || !/^\d+$/.test(this.operPhone)) {
                this.$message({
                    message: '请输入正确的电话号码',
                    type: 'warning'
                });
                return;
            }
            if ((this.operInfoObject.userName != this.operName
                || this.operInfoObject.userMsisdn != this.operPhone
                || this.operInfoObject.duty != this.operPermission)
                && adminGroupIdsKey.toString() != this.selectGroup.toString()) {
                updateType = '3';
            }
            let param = {
                "userId": this.operInfoObject.userId,
                "userMsisdn": this.operPhone,
                "userName": this.operName,
                "duty": this.operPermission == '集团管理员' ? '1' : '2',
                "cityId": '',
                "adminGroupIds": JSON.stringify(adminGroupIdsKey),
                "updateType": updateType
            }
            this.$http.post('/lbs/usercenter/operator/updateOperator', param).then(res => {
                if (res.data.retCode == '0') {
                    this.$message({
                        message: res.data.retMsg,
                        type: 'success'
                    });
                    this.closePop()
                } else {
                    this.$message({
                        message: res.data.retMsg,
                        type: 'error'
                    });
                }
            })
        },
        judgeNameRepeat(userName,userAcct,userPhone){
            if (!userName && !userAcct && !userPhone){
                return;
            }
            if (this.operInfoObject.userName == this.operName
                && this.operInfoObject.userMsisdn == this.operPhone
                && this.operInfoObject.userAcct == this.operCount) {
                if (userName && !userAcct && !userPhone){
                    this.nameRepeatFlag = false;
                }else if (!userName && userAcct && !userPhone){
                    this.accountRepeatFlag = false;
                }else if (!userName && !userAcct && userPhone){
                    this.phoneRepeatFlag = false;
                }
                return;
            }
            let param = {
                "userName": userName,
                "userAcct": userAcct,
                "userMsisdn":userPhone,
                "unLoadFlg":true
            }
            this.$http.post('/lbs/usercenter/operator/judgeNameRepeat',param).then(res =>{
                if (res.data.retCode == '0') {
                    if (res.data.data == '1') {
                        if (userName && !userAcct && !userPhone){
                            this.nameRepeatFlag = true;
                        }else if (!userName && userAcct && !userPhone){
                            this.accountRepeatFlag = true;
                        }else if (!userName && !userAcct && userPhone){
                            this.phoneRepeatFlag = true;
                        }
                    }else{
                        if (userName && !userAcct && !userPhone){
                            this.nameRepeatFlag = false;
                        }else if (!userName && userAcct && !userPhone){
                            this.accountRepeatFlag = false;
                        }else if (!userName && !userAcct && userPhone){
                            this.phoneRepeatFlag = false;
                        }
                    }
                } else {
                    if (userName && !userAcct && !userPhone){
                        this.nameRepeatFlag = true;
                    }else if (!userName && userAcct && !userPhone){
                        this.accountRepeatFlag = true;
                    }else if (!userName && !userAcct && userPhone){
                        this.phoneRepeatFlag = true;
                    }
                    this.$message({
                        message: res.data.retMsg,
                        type: 'error'
                    });
                }
            })
        }
    },
    watch:{
        newOperFlag(val){
            if (val){
                this.selectGroupSearch();
            }
        },
        updateOperFlag(val){
            if (val){
                this.infoDeal();
            }
        }
    }
}
</script>

<style scoped lang="less">
.pss-main-oper{
    position: fixed;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
}
.pss-main-body{
    width: 100%;
    position: absolute;
    top: 0;
    bottom: 0;
    background:#000000;
    opacity: 15%;
    z-index: 99;
}
.pss-main-pop{
    width: auto;
    height: auto;
    min-width: 680px;
    border-radius: 15px;
    background:#fff;
    z-index: 100;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
}
.pss-pop-top{
    width: 100%;
    height: 60px;
    background: #F9F9F9;
    z-index: 101;
    border-radius: 15px 15px 0 0;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
}
.pss-striping{
    width: 16%;height: 1px;background: #D1D1D1;
}
.pss-striping.blue{background: #007AFF;}
.pss-base-info{
    font-size: 12px;
    color: #656565;
}
.pss-plan-form{
    padding: 0px 30px 7px;
    position: relative;
}

.associates-box{
    width: auto;
    min-width: 300px;
    margin: 15px 20px;
}
.associates-box-tree{
    background:#f7f7f7;
    height: 300px;
    overflow: auto;
    padding: 10px 5px;
    box-sizing: border-box;
}
.info-module{
    display: flex;
}
.form-label-name{
    font-size: 14px;
    line-height: 41px;
    padding-right: 12px;
    color: #606266;
}
</style>
<style lang="less">
.pss-main-oper {
    .el-input__inner {
        height: 24px;
        line-height: 24px;
        width: 170px;
    }
    .el-input__inner.active{
        border: 1px red solid;
    }
    .el-input {
        width: auto;
    }
    .pss-demonstration{
        font-size: 14px;
        color: #606266;
    }
    .el-date-editor .el-range__icon{
        line-height: 16px;
    }
    .el-date-editor .el-range-input, .el-date-editor .el-range-separator{
        font-size: 12px;
    }
    .el-date-editor .el-range-separator{
        line-height: 16px;
    }
    .el-date-editor .el-range__close-icon{
        line-height: 16px;
    }
    .el-date-editor--daterange.el-input, .el-date-editor--daterange.el-input__inner, .el-date-editor--timerange.el-input, .el-date-editor--timerange.el-input__inner{
        width: 220px;
    }
    .el-form-item{
        margin-bottom: 0;
    }
    .el-radio-button__inner{
        padding: 2px 5px;
        font-size: 12px;
    }
    .el-checkbox{
        margin-right: 15px;
    }
    .el-tree{
        background: none;
    }
    .el-input--small .el-input__inner{
        height: 24px;
        line-height: 24px;
    }
    .el-form-item__content{
        padding-top: 10px;
        line-height: 24px;
        position: relative;
        font-size: 14px;
    }
}
.el-table::before{
    height: 0;
}
</style>
